package com.goofengcn.website.application.util.pager;

import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

import com.goofengcn.website.web.controller.AnjieConstants;

/**
 * 接收在sql:query中生成的查询结果记录数，然后构造url或表单的hidden变量的参数，父类
 */
public class PageBuildTag
    extends TagSupport {
    private JspWriter out;

    // 日志记录器
    //private Log log = MetLogFactory.getLogger(PageBuildTag.class);
    public String targetFormNo = null;
    public String thereFormNo = null;
    private String strPageSize;

    //public String targetFormNo=null; //form的编号，分页的form
    //public String thereFormNo=null; //form的编号，填写页码的form

    public PageBuildTag() {
        super();
    }

    private void buildPageCommand(String sFormName, int nPageSize, int nPageNo,
                                  int nBeginRow, int nTotalRows,
                                  int nTotalPages,
                                  String sTargetFormNo, String sThereFormNo,
                                  String nPageSizeStep) {
        int nTargetPage;

        try {
            out.println("<script language=\"JavaScript\">");
            out.println("function isDigit(num) {");
            out.println("       var lng;");
            out.println("       i = 0;");
            out.println("       lng = num.length;");
            out.println("       while (i < lng) {");
            out.println(
                "           if (num.charAt(i) < '0' || num.charAt(i) > '9') {");
            out.println("               return \"false\";");
            out.println("           }");
            out.println("           i++;");
            out.println("       }");
            out.println("       return \"true\";");
            out.println("}");

            out.println(
                "function goThere(thereFormNo, targetFormNo, pageSize, totalPage, totalRows) {");
            out.println(
                "   if (document.forms[thereFormNo].goText.value == \"\") {");
            out.println("       alert(\"请填写页数\");");
            out.println("       return false;");
            out.println("   }");
            out.println(
                "   if (isDigit(document.forms[thereFormNo].goText.value) == \"false\") {");
            out.println("       alert(\"请填写数字\");");
            out.println("       return false;");
            out.println("   }");

            out.println("   if (document.forms[thereFormNo].goText.value <= 0 || document.forms[thereFormNo].goText.value > totalPage) {");
            out.println("       alert(\"页数不正确\");");
            out.println("       return false;");
            out.println("   }");

            out.println("   goTargetPage(targetFormNo, pageSize, document.forms[thereFormNo].goText.value,totalRows);");
            out.println("   return true;");
            out.println("}");

            out.println(
                "function goTargetPage(targetFormNo, pageSize, pageNo,totalRows) {");
            out.println("var beginRow = (pageNo - 1) * pageSize + 1;");
            //out.println("alert(beginRow + \" \" + pageNo + \" \" + pageSize + \" \" + totalRows);");

            out.println(
                "document.getElementById(\"beginRow\").value = beginRow;");
            out.println("document.getElementById(\"pageNo\").value = pageNo;");
            out.println(
                "document.getElementById(\"pageSize\").value = pageSize;");
            out.println(
                "document.getElementById(\"totalRows\").value = totalRows;");
            //out.println("alert(document.forms[targetFormNo].action);");
            out.println("var actionurl = document.forms[targetFormNo].action ;");
            out.println("var mySplitResult = actionurl.split(\"/\");");
            out.println("var url = \"\";");
            out.println("for (i=0;i<=mySplitResult.length-1;i++){");
            out.println("if(i!=mySplitResult.length-1)	url += mySplitResult[i] +\"/\" ;");
            out.println("else if(i==mySplitResult.length-1)	url += parseInt(pageNo)-1+'';");
            out.println("}");
            
            //out.println("alert(\"url == \"+url);");
            out.println("document.forms[targetFormNo].action = url;");
            out.println("document.forms[targetFormNo].submit();");
            out.println("}");
            out.println("</script>");

            out.println(
                "<table width=100% border=0 cellspacing=0 cellpadding=0>");
            out.print("<form name=goThereForm>");
            out.println("<tr>");
            out.println("<td align=right>");
            if (nTotalRows != 0) {
                if (nBeginRow + nPageSize > nTotalRows) {
                    if (nBeginRow<=nTotalRows){
                        out.print("第<strong>" + nBeginRow + "</strong>-<strong>" +
                                  nTotalRows +
                                  "</strong>条");
                    }
                    out.print("(共<strong>" + (nTotalRows) +"</strong>条) ");
                }
                else {
                    if (nBeginRow<=nTotalRows){
                        out.print("第<strong>" + nBeginRow +
                                  "</strong>-<strong>" +
                                  (nBeginRow + nPageSize - 1) +
                                  "</strong>条");
                    }
                    out.print("(共<strong>" +(nTotalRows) + "</strong>条) ");
                }
            }
            else {
                    out.print(
                            "第<strong>0</strong>-<strong>0</strong>条(共<strong>0</strong>条) ");

            }
            if (nBeginRow<=nTotalRows){
                out.print(" 第<strong>" + nPageNo + "</strong>页");
            }
            out.print("(共<strong>" +
                      nTotalPages +
                      "</strong>页) ");
            if (nPageNo == 1) {
                out.print("首页");
            }
            else {
                nTargetPage = 1;
                out.print("<a href=\"javascript:goTargetPage(" + sTargetFormNo +
                          ", " +
                          nPageSize + ", " + nTargetPage + ", " + nTotalRows +
                          ")\"><font color=\"#FF8040\">");
                out.print("首页");
                out.print("</font></a>");
            }
            out.print("|");

            if (nPageNo > 1) {
                nTargetPage = nPageNo - 1;
                out.print("<a href=\"javascript:goTargetPage(" + sTargetFormNo +
                          ", " +
                          nPageSize + ", " + nTargetPage + ", " + nTotalRows +
                          ")\"><font color=\"#FF8040\">");
                out.print("前页");
                out.print("</font></a>");
            }
            else {
                out.print("前页");
            }
            out.print("|");

            if (nPageNo < nTotalPages) {
                nTargetPage = nPageNo + 1;
                out.print("<a href=\"javascript:goTargetPage(" + sTargetFormNo +
                          ", " +
                          nPageSize + ", " + nTargetPage + ", " + nTotalRows +
                          ")\"><font color=\"#FF8040\">");
                out.print("后页");
                out.print("</font></a>");
            }
            else {
                out.print("后页");
            }
            out.print("|");

            if (nPageNo < nTotalPages) {
                nTargetPage = nTotalPages;
                out.print("<a href=\"javascript:goTargetPage(" + sTargetFormNo +
                          ", " +
                          nPageSize + ", " + nTargetPage + ", " + nTotalRows +
                          ")\"><font color=\"#FF8040\">");
                out.print("尾页");
                out.print("</font></a>");
            }
            else {
                out.print("尾页");
            }
            out.print("|");

            if (nTotalPages > 1) {
                out.print("转到:<input type=text maxLength=5 name=goText size=3" +
                    " style=\"BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid;" +
                    " FONT-SIZE: 10px; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid ;" +
                    " font-family: Arial, Helvetica, sans-serif; width: 18px\"" +
                    " onKeyPress=\"if (event.keyCode == 13) return goThere(" +
                    sThereFormNo + ", " +
                    sTargetFormNo + ", " + nPageSize + ", " + nTotalPages +
                    ", " + nTotalRows +
                    ")\">&nbsp;页");
                out.print(
                    "<input type=text name=goTextNone style=display:none>");
                out.print("<input name=goRun type=button  onFocus=\"this.blur()\" style=\"BORDER-RIGHT: #000000 1px solid;" +
                          " BORDER-TOP: #000000 1px solid; FONT-SIZE: 9px; BORDER-LEFT: #000000 1px solid;" +
                          " BORDER-BOTTOM: #000000 1px solid ; font-family: Arial, Helvetica, sans-serif\" value=\"GO\" ");
                out.println("onClick=\"goThere(" + sThereFormNo + ", " +
                            sTargetFormNo +
                            ", " + nPageSize + ", " + nTotalPages + ", " +
                            nTotalRows + ")\">");
            }
            else {
                out.print("转到:<input type=text maxLength=5 name=goText size=3" +
                    " style=\"BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid;" +
                    " FONT-SIZE: 10px; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid ;" +
                    " font-family: Arial, Helvetica, sans-serif; width: 18px\"" +
                    " disabled >&nbsp;页&nbsp;");
                out.print(
                    "<input type=text name=goTextNone style=display:none>");
                out.print("<input name=goRun type=button  onFocus=\"this.blur()\" style=\"BORDER-RIGHT: #000000 1px solid;" + " BORDER-TOP: #000000 1px solid; FONT-SIZE: 9px; BORDER-LEFT: #000000 1px solid;" +
                          " BORDER-BOTTOM: #000000 1px solid ; font-family: Arial, Helvetica, sans-serif\" value=\"GO\" ");
                out.println(" disabled >");
            }

//          edit by johnson @ 2007-09-06 去掉每页多少条 注释掉下面的
//           if (nPageSizeStep != null) {
//                StringBuffer sb = new StringBuffer();
//                if (nPageSizeStep.indexOf("/") != -1) {
//                    String[] stepNos = com.metinform.util.web.StringProcessor.
//                        splitToStrings("/", nPageSizeStep, true);
//                    if (stepNos != null && stepNos.length > 0) {
//                        out.print("|");
//                        sb.append("每页&nbsp;");
//                        sb.append(
//                            "<select name='buildseletpagesize' value='" +
//                            nPageSize + "' onchange='javascript:goTargetPage(" +
//                            sTargetFormNo + ", this.value, 1," + nTotalRows +
//                            ")'>");
//                        sb.append("\n");
//                        for (int i = 0; i < stepNos.length; i++) {
//                            String tmeStep = stepNos[i];
//                            sb.append("<option value='" + tmeStep + "'");
//                            if (String.valueOf(nPageSize) != null &&
//                                tmeStep.equals(String.valueOf(nPageSize))) {
//                                sb.append(" selected ");
//                            }
//                            sb.append(">" + tmeStep + "</option>");
//                            sb.append("\n");
//                        }
//                        sb.append("</select>");
//                        sb.append("条");
//                        sb.append("\n");
//                    }
//                }
//                
//                out.println(sb.toString());
//            }//
            
            //edit by johnson @ 2009-12-08 修改tag ，将hidden变量自动加上
            out.println("<input type=\"hidden\" name=\"beginRow\" id=\"beginRow\" value=\""+nBeginRow+"\"/>");
            out.println("<input type=\"hidden\" name=\"pageSize\" id=\"pageSize\" value=\""+nPageSize+"\"/>");
            out.println("<input type=\"hidden\" name=\"pageNo\" id=\"pageNo\" value=\""+nPageNo+"\"/>");
            out.println("<input type=\"hidden\" name=\"totalRows\" id=\"totalRows\" value=\""+nTotalRows+"\"/>");
            
            out.println("</td>");
            out.println("</tr>");
            out.println("</form>");
            out.println("</table>");

        }
        catch (Exception e) {
            //System.out.println("=========PageBuilderTag===========" + e.toString());
        }
    }

    public int doStartTag() throws JspException {
        try {
            int totalPages; //总页数
            int totalRows; //总页数
            int pageSize; //一页显示的记录数
            int pageNo; //当前页面号
            int beginRow; //开始记录
            String formName; //表单的name
            int scope;
            HttpServletRequest request = (HttpServletRequest) pageContext.
                getRequest();
            out = pageContext.getOut();
            scope = PageContext.PAGE_SCOPE;

            formName = (String) request.getAttribute("formName"); //取得在标记head中设置的formAction变量的值
            if (formName == null) {
                formName = request.getParameter("formName");
            }

            //Integer ps = (Integer) pageContext.getAttribute("pageSize", scope);
            String tmpPageSize = (String) request.getAttribute("pageSize");
            tmpPageSize = pageContext.getRequest().getParameter("pageSize");
            if (tmpPageSize == null) {
                tmpPageSize = request.getParameter("pageSize");
            }
            if (strPageSize == null ||"".equals(strPageSize)||"null".equals(strPageSize)) {
                if (tmpPageSize == null) {
                    //WebConfig webConfig = WebConfig.getInstance();
//                    pageSize = Integer.parseInt(webConfig.getProperty("default.page.size"));
                    pageSize = AnjieConstants.PAGESIZE; //Integer.parseInt("1");//每页显示多少条数据
                }
                else {
                    pageSize = Integer.parseInt(tmpPageSize);
                }
            }
            else {
                pageSize = Integer.parseInt(strPageSize); //取得JSP变量pageSize
            }

            String strPageNo = (String) request.getParameter("pageNo");
            if (strPageNo == null ||"".equals(strPageNo)||"null".equals(strPageNo)) {
                strPageNo = (String)request.getAttribute("pageNo");
            }

            if (strPageNo == null ||"".equals(strPageNo)||"null".equals(strPageNo)) {
                pageNo = 1;
            }
            else {
                pageNo = Integer.parseInt(strPageNo); //取得JSP变量pageNo
            }

            String strBeginRow = (String) request.getParameter("beginRow");

            if (strBeginRow == null ||"".equals(strBeginRow)||"null".equals(strBeginRow)) {
                strBeginRow = (String)request.getAttribute("beginRow");
            }

            if (strBeginRow == null||"".equals(strBeginRow)||"null".equals(strBeginRow)) {
                beginRow = 1;
            }
            else {
                beginRow = Integer.parseInt(strBeginRow); //取得JSP变量beginRow
            }

            String strTotalRows = (String) request.getAttribute("totalRows");
            if (strTotalRows == null||"".equals(strTotalRows)||"null".equals(strTotalRows)) {
                strTotalRows = request.getParameter("totalRows");
            }

            if (strTotalRows == null||"".equals(strTotalRows)||"null".equals(strTotalRows)) {
                totalRows = 0;
            }
            else {
                totalRows = Integer.parseInt(strTotalRows); //取得JSP变量totalRows
            }

            totalPages = (totalRows + pageSize - 1) / pageSize; //记算总页数
            if (totalPages <= 0) {
                totalPages = 1;
            }


           if (beginRow > totalRows && pageNo != 1) {
             beginRow = beginRow - pageSize;
             pageNo--;
           }
            request.removeAttribute("pageNo");
            request.removeAttribute("beginRow");

            buildPageCommand(formName, pageSize, pageNo, beginRow, totalRows,
                             totalPages, targetFormNo, thereFormNo, pageStep);

        }
        catch (Exception e) {
            //System.out.println("=========PageBuilderTag===========" + e.toString());
        }

        //return SKIP_BODY;             //不包含body
        //return EVAL_BODY_BUFFERED;    //包含interact类型的body
        return SKIP_BODY; //包含no interact类型的body
    }

    public void release() {
    }

    public String getTargetFormNo() {
        return targetFormNo;
    }

    public void setTargetFormNo(String targetFormNo) {
        this.targetFormNo = targetFormNo;
    }

    public String getThereFormNo() {
        return thereFormNo;
    }

    public void setThereFormNo(String thereFormNo) {
        this.thereFormNo = thereFormNo;
    }

    public String getStrPageSize() {
        return strPageSize;
    }

    public void setStrPageSize(String strPageSize) {
        this.strPageSize = strPageSize;
    }

    private String pageStep = "10/15/30/50/100";
    public String getPageStep() {
        return pageStep;
    }

    public void setPageStep(String pageStep) {
        this.pageStep = pageStep;
    }
}
